package jia.core.graphics;

import jia.game.GenericFlags;
import org.apache.log4j.Logger;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

//===============================================

/**
 * @author <a href="mailto:kintar@infinities-within.net">Kintar</a>
 */
public class FlatImageManager {
    private static final Logger log = Logger.getLogger(FlatImageManager.class);
    private static Map<String, BufferedImage> images = new HashMap<String, BufferedImage>();
    
    //===============================================
    /**
     */
    private FlatImageManager() {
        // GNDN
    }
    
    //===============================================
    /**
     * @param imageResource
     * @return
     */
    public static BufferedImage getImage(String imageResource) {
        if (!images.containsKey(imageResource)) {
            loadImage(imageResource);
        }
        
        return images.get(imageResource);
    }
    
    //===============================================
    /**
     * @param imageResource
     */
    private static void loadImage(String imageResource) {
        try {
            URL resourceUrl = FlatImageManager.class.getClassLoader().getResource(imageResource);
            if (GenericFlags.debugMessages) {
                log.debug(resourceUrl.toString());
            }
            BufferedImage img = ImageIO.read(resourceUrl);
            images.put(imageResource, img);
        } catch (Exception e) {
            if (GenericFlags.warningMessages){
                log.warn("Could not load image resource '" + imageResource + "'");
            }
        }
    }
    
    //===============================================
    /**
     */
    public static void purge() {
        if (GenericFlags.debugMessages) {
            log.debug("Recieved purge request");
        }
        images.clear();
    }
}
